#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Datetime: 2022/9/8 18:32
# @Author  : CHENWang
# @Site    : 
# @File    : loanscan.py
# @Software: PyCharm

"""
脚本说明: 从loanscan上获取历史借贷费率
"""

import time
import datetime
from quant_researcher.quant.project_tool.wrapper_tools.common_wrappers import deco_retry
from dateutil.tz import *
import pandas as pd
import requests
import json


@deco_retry(retry=5, retry_sleep=15)
def get_lend_borrow_fee_rate(protocol='aave', lend_or_borrow='borrow', asset='USDC'):
    """

    :param protocol: 支持'aave', 'compound', 'makerdao', 'dydx'
    :param lend_or_borrow: 查询存款利率，还是借贷利率
    :param asset: 存贷的资产
    :return:
    """
    protocol_dict = {'aave': 'AaveVariable', 'compound': 'CompoundV2', 'dydx': 'dYdX', 'makerdao': 'MakerDaoV2'}
    lend_or_borrow_dict = {'lend': 'Supply', 'borrow': 'Borrow'}

    start = int(time.mktime(datetime.datetime(2019, 1, 1, 0, 0, 0, tzinfo=tzutc()).timetuple()))

    header = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36',
              'cookie': 'cf_clearance=X12hxzfquZttFm2ue5Sw.LIuMTGJSZ0lh4kcP_fS_Cg-1638775214-0-250; _ga=GA1.2.1414204356.1638775216; _gid=GA1.2.448679075.1638775216; _xicah=fe0ed320-57dfa72f; __gads=ID=41b848319f12f7e0:T=1638775219:S=ALNI_MaX6DS7JjwRHwe411DzL2HlXWQ9LQ',
              'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9'}
    url = f'https://api.loanscan.io/v1/interest-rates/historical?provider={protocol_dict[protocol]}&interestRateDomain={lend_or_borrow_dict[lend_or_borrow]}' \
          f'&intervaltype=Day&startDateTimestamp={start}&tokenSymbol={asset}'

    res = requests.get(url, headers=header, timeout=15)
    res = pd.DataFrame(json.loads(res.text))
    res['date'] = [i[:10] for i in res['date']]
    res.set_index('date', inplace=True)
    res.rename(columns={'value': f'{lend_or_borrow}_rate'}, inplace=True)
    if (res == 0).all().values[0]:
        print(f'获取的数据全为0， 请检查入参是否正常protocol={protocol}, lend_or_borrow={lend_or_borrow}, asset={asset}')
        return None

    return res


if __name__ == '__main__':
    df = get_lend_borrow_fee_rate(protocol='aave', lend_or_borrow='borrow', asset='USDC')